import { getTaskList as getTaskListApi, getTaskResult as getTaskResultApi } from '@/api/scoring'

interface ScoringState {
  taskList: any[]
  currentTask: any | null
  pagination: {
    current_page: number
    page_size: number
    total: number
    total_pages: number
  }
  loading: boolean
}

const scoring = {
  namespaced: true,
  state: (): ScoringState => ({
    taskList: [],
    currentTask: null,
    pagination: {
      current_page: 1,
      page_size: 10,
      total: 0,
      total_pages: 0
    },
    loading: false
  }),
  mutations: {
    SET_TASK_LIST(state, { items, pagination }) {
      state.taskList = items
      state.pagination = pagination
    },
    SET_CURRENT_TASK(state, task) {
      state.currentTask = task
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    UPDATE_TASK_STATUS(state, { taskId, status }) {
      const taskIndex = state.taskList.findIndex(task => task.task_id === taskId)
      if (taskIndex !== -1) {
        state.taskList[taskIndex].status = status
        state.taskList[taskIndex].status_name = getStatusName(status)
      }
    }
  },
  actions: {
    async getTaskList({ commit }, params: any) {
      commit('SET_LOADING', true)
      try {
        const response = await getTaskListApi(params)
        if (response.success) {
          commit('SET_TASK_LIST', {
            items: response.data.items,
            pagination: response.data.pagination
          })
          return { success: true }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('Get task list error:', error)
        return { success: false, message: '获取任务列表失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },

    async getTaskResult({ commit }, taskId: number) {
      commit('SET_LOADING', true)
      try {
        const response = await getTaskResultApi({ task_id: taskId })
        if (response.success) {
          commit('SET_CURRENT_TASK', response.data)
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('Get task result error:', error)
        return { success: false, message: '获取任务结果失败' }
      } finally {
        commit('SET_LOADING', false)
      }
    },

    clearCurrentTask({ commit }) {
      commit('SET_CURRENT_TASK', null)
    }
  },
  getters: {
    taskList: (state) => state.taskList,
    currentTask: (state) => state.currentTask,
    pagination: (state) => state.pagination,
    isLoading: (state) => state.loading
  }
}

// 辅助函数
function getStatusName(status: number): string {
  const statusMap = {
    1: '待处理',
    2: '分析中',
    3: '已完成',
    4: '失败'
  }
  return statusMap[status] || '未知'
}

export default scoring